package edu.pku.hawk.controller.util;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.HashMap;

import edu.pku.hawk.datasource.SensorType;
import edu.pku.hawk.service.bo.RowSensorData;

public class SensorAllData implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -7358209520160225701L;
	// int device_address = 4;
	// int io_value = 0x02;
	// int pressure_1;
	// int pressure_2;
	// int pressure_3;
	// int pressure_4;
	// Timestamp time = new Timestamp(System.currentTimeMillis());
	public int device_address;
	public int io_value;
	public int pressure_1;
	public int pressure_2;
	public int pressure_3;
	public int pressure_4;
	public Timestamp time;

	public static RowSensorData parse(String sensorType, int sensorId,
			HashMap<Integer, SensorAllData> sensorDataByDevice) {
		SensorType sensor = SensorType.valueOf(sensorType);
		if (sensor == SensorType.sensor_pressure || sensor == SensorType.sensor_infrared
				|| sensor == SensorType.sensor_metal) {

			Config config = Config.Singleton.Instance;
			DetectorInfo dinfo = config.getDetectorInfo(((Integer) (sensorId)).toString());

			String tableName = "sensors";
			int deviceAddr = dinfo.deviceAddr;
			if (deviceAddr != 1 && deviceAddr != 2 && deviceAddr != 3 && deviceAddr != 4)
				return RowSensorData.Empty;
			int switchNum = dinfo.switchNum;
			if (switchNum <= 0 || switchNum > 8)
				return RowSensorData.Empty;

			RowSensorData tm = RowSensorData.Empty;

			SensorAllData allData = sensorDataByDevice.get(deviceAddr);
			if (allData != null) {

				Object value = null;
				if (sensor == SensorType.sensor_infrared || sensor == SensorType.sensor_metal) {
					int iovalue = allData.io_value;
					int mask = 0x80;
					for (int i = 1; i < switchNum; i++) {
						mask >>= 1;
					}
					value = ((iovalue & mask) == 0) ? 0 : 1;
					java.sql.Timestamp time = allData.time;
					tm = new RowSensorData(sensorId, value, time);

				} else if (sensor == SensorType.sensor_pressure) {
					switch (switchNum) {
					case 1:
						value = allData.pressure_1;
						break;
					case 2:
						value = allData.pressure_2;
						break;
					case 3:
						value = allData.pressure_3;
						break;
					case 4:
						value = allData.pressure_4;
						break;
					}
					java.sql.Timestamp time = allData.time;
					tm = new RowSensorData(sensorId, value, time);
				}
			}
			return tm;
		} else {
			return RowSensorData.Empty;
		}
	}
}